/**
 *
 * http配置
 *
 */
// 引入axios以及element ui中的loading和message组件
import axios from 'axios';
import {
    refeshToken,
} from '@/api/user';
import errorCode from '@/const/errorCode';
import {
    validatenull,
} from '@/util/validate';
import { Message, Loading } from 'element-ui';
import store from '../store';

axios.defaults.timeout = 30000;

let cfg,
    loading;

// HTTPrequest拦截
axios.interceptors.request.use((config) => {
    if (config.headers.loading !== false) {
        loading = Loading.service({
            lock: true,
            text: '物业君努力加载中',
            background: 'rgba(0, 0, 0, 0)',
        });
    }
    config.headers['client-type'] = 'wuye';
    if (store.getters.token && config.auth !== false) {
        config.headers.Authorization = `Bearer ${store.getters.token}`;
    }
    cfg = config;
    return config;
}, (error) => {
    Toast({
        message: errorCode.default,
        duration: 2000,
    });
    return Promise.reject(error);
});
// HTTPresponse拦截
axios.interceptors.response.use((res) => {
    loading.close();
    const data = res.data;
    const status = data.status;
    const msg = data.msg;
    return res;
}, (error) => {
    const errMsg = error.toString();
    const code = errMsg.substr(errMsg.indexOf('code') + 5);
    loading.close();
    if (cfg.headers.loading != false) {
        Message.warning({
            message: errorCode[code] || errorCode.default,
            duration: 1500,
        });
    }
    return error;
});

export default axios;